/**********************************************************************************
 * Copyright (c) 2012 - 2012,  parallel, All right reserved
 * Title: com.adc.parallel.daemon  BaseTimerThread.java 
 * @author shen  shenqiao2012@163.com 
 *  2012-11-20 下午2:50:32 
 *********************************************************************************/


package com.adc.parallel.daemon;

import com.adc.parallel.constants.ThreadConstant;


/**
 * 
 * Description: a thread factory which produce time limited thread
 * @author shen  shenqiao2012@163.com
 */
public abstract class BaseTimerThread extends Thread {
	
	/**
	 * max live time
	 */
	private long maxLive;
	/**
	 * cycle time
	 */
	private long cycle;
	/**
	 * exit or not
	 */
	private boolean exit=false;
	
	private int preRst=ThreadConstant.EXEC_FAIL;
	private int overRst=ThreadConstant.EXEC_FAIL;
	
	/**
	 * 
	 * Description: do something in cycle 
	 * author:  shen
	 * @return int
	 */
	public abstract int operaPerCycle();
	
	/**
	 * 
	 * Description: do something when time out 
	 * author:  shen
	 * @return int
	 */
	public abstract int operaOnTimeOut();
	
	/** 
	 * constructor
	 */
	public BaseTimerThread(long maxLive,long cycle) {
		this.maxLive=maxLive;
		this.cycle=cycle;
	}
	
	/**
	 * Description:  
	 * @see java.lang.Thread#run() 
	 */
	public void run() {
		long time=0L;
		try {
			while (!exit) {
				preRst=operaPerCycle();
				sleep(cycle);
				time=time+cycle;
				if ((time+cycle)>maxLive) {
					overRst=operaOnTimeOut();
				}
			}
//			System.out.println("[INFO]\tExit ["+this.getName()+"] Thread!\n\t" +
//					"The operaPerCycle result is ["+preRst+"]; The operaOnTimeOut result is ["+overRst+"].");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("Daemon thread appeared Exception!");
		}
	}

	/**
	 * @param exit the exit to set
	 */
	public void setExit(boolean exit) {
		this.exit = exit;
	}

	/**
	 * @return the preRst
	 */
	public int getPreRst() {
		return preRst;
	}

	/**
	 * @return the overRst
	 */
	public int getOverRst() {
		return overRst;
	}
	
}
